<template>
  <div class="disqualified-reason-dialog">
    <basic-dialog
      :visible="show"
      minWidth="1000px"
      title="不良原因明细"
      :isShowClose="true"
      :isFullScreen="true"
      @close="$emit('close')"
    >
      <!-- 显示信息  -->
      <div>
        <div class="q-pa-md padding-l-20 padding-r-20">
          <div class="row">
            <div class="col">车间:{{location.workshop}}</div>
            <div class="col">原因：{{location.reason}}</div>
            <div class="col row">
              <div class="col" style="margin-left:-35px">统计时间：{{location.dateTime}}</div>
              <div>
                <q-btn class="btn col" outline color="primary" @click="exportList" label="导出Excel" />
              </div>
            </div>
          </div>
        </div>
        <!-- 图表-->
        <q-table
          :data="tableData"
          :columns="columns"
          row-key="id"
          id="reasonTable"
          class="myTable scroll scroll-box"
          style="margin: 0px 0 24px 0; max-height: 384px"
          hide-bottom
          :pagination.sync="pagination"
          separator="cell"
          no-data-label="暂无数据"
          :loading="isTableLoading"
          color="primary"
        >
          <template v-slot:header="props">
            <q-tr>
              <q-th
                v-for="col in props.cols.filter(v=>v.cols === 1)"
                :key="col.name"
                :props="props"
                :rowspan="2"
                :colspan="col.cols"
              >{{ col.label }}</q-th>
              <q-th v-for="item in colsData" :key="item.name" rowspan="1" colspan="1">{{item.label}}</q-th>
            </q-tr>
            <q-tr>
              <q-th
                v-for="col in props.cols.filter(v=>v.cols === 2)"
                :key="col.name"
                :props="props"
              >{{col.label}}</q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td v-for="item in columns" :key="item.field">
                <q-btn
                  flat
                  color="primary"
                  style="margin: 0 30%"
                  v-if="isShowBadBtn(item.field, props.row[item.field])"
                  @click="onLookDetail(props.row, item)"
                  :label="props.row[item.field]"
                ></q-btn>
                <span v-else>{{props.row[item.field]}}</span>
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
      <!--  分页-->
      <!-- <pagination v-model="pagination.page"
                    :page-size="pagination.rowsPerPage"
                    :total="pagination.rowsNumber"
                    @changePageSize="onPageSizeChange"
                    @changePage="onPageChange"
      style="margin-bottom: 20px" />-->
    </basic-dialog>
    <defect-dialog
      :show="isDefect"
      :defectRowData="defectRowData"
      @close="isDefect = false"
      ref="defectDialog"
    ></defect-dialog>
  </div>
</template>

<script>
// import Pagination from '../../../components/pagination/index'
import defectDialog from './defect-dialog'
import { getDailyBadReport } from '../../../boot/statistics/stop-reason'
import _ from 'lodash'
import exportJs from './export'
import moment from 'moment'
import { mapGetters } from 'vuex'
// import XLSX from 'xlsx'

export default {
  name: 'disqualified-reason-dialog',
  components: {
    ...mapGetters([
      'userInfo'
    ]),
    // Pagination,
    defectDialog
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    rowData: Object,
    queryParams: Object,
    stopType: String
  },
  data () {
    return {
      isTableLoading: false,
      isDefect: false,
      // 表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      // 显示车间的信息
      location: {
        workshop: '',
        reason: '',
        dateTime: ''
      },
      // 表格头部数据
      tableColumns: [],
      // 表格内容
      tableData: [],
      defectRowData: {},
      queryData: {},
      colsData: [],
      rowParams: {}
    }
  },
  computed: {
    columns () {
      const columns = [
        { name: 'indexId', field: 'indexId', label: '序号', align: 'left', cols: 1 },
        {
          name: 'productName',
          field: 'productName',
          label: '产品名称',
          align: 'left',
          cols: 1
        }
      ]
      return [...columns, ...this.tableColumns]
    }
  },
  watch: {
    // 监听查询元素
    queryParams: {
      handler (newPro) {
        if (newPro) {
          this.queryData = newPro
        }
      },
      deep: true,
      immediate: true
    },
    // 监听行元素
    rowData: {
      handler (newPro) {
        if (newPro) {
          this.rowParams = newPro
        }
      },
      deep: true,
      immediate: true
    },
    // 监听原因类别
    stopType: {
      handler (newPro) {
        this.causeStopType = newPro
      },
      immediate: true,
      deep: true
    },
    // 监听是否打开
    show (newPro) {
      if (newPro) {
        this.getDailyBadReport()
      }
    }
  },
  methods: {
    getTableHeader () {
      let columns = [
        {
          label: '序号'
        },
        {
          label: '产品名称'
        }
      ]
      columns = [
        ...columns,
        ...this.colsData
      ]
      columns = columns.map(v => v.label)
      return columns
    },
    isShowBadBtn (val, row) {
      return val.indexOf('badSeconds') > -1 && !_.isUndefined(row)
    },
    // 导出xls 样式
    exportList () {
      const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语桢物联'
      const stopReason = `不良原因分析产品明细`
      const undesirableReason = `不良原因： ${this.location.reason}`
      const countTime = `统计时间： ${this.location.dateTime}`
      const position = `车间: ${this.location.workshop}`
      const tableHead = this.getTableHeader()
      const tableData = this.getTableData(this.tableData, tableHead)
      const sheetName = `${this.getDate(this.queryData.dateRange[0])}-${this.getDate(this.queryData.dateRange[1])}-不良原因分析产品明细报表`
      const excelName = `${this.getDate(this.queryData.dateRange[0])}-${this.getDate(this.queryData.dateRange[1])}-${this.location && this.location.workshop}-不良原因分析产品明细报表`
      // console.log(tableHead)
      // console.log(this.tableData)
      // console.log('tableData', tableData)
      exportJs.exportCustomerExcel(companyName, stopReason, position, tableHead, tableData, excelName, undesirableReason, countTime, sheetName)
    },
    // 获取表格数据
    getTableData (tableData, tableHead) {
      var result = []
      tableData.forEach(v1 => {
        const v1KesArr = Object.keys(v1)
        const item = []
        tableHead.forEach((v2, index) => {
          if (v2 === '序号') {
            item.push(v1.indexId)
          } else if (v2 === '产品名称') {
            if (this.stopType === '1') {
              item.push(v1.productName)
            } else {
              item.push(v1.productName)
            }
          } else {
            let findI = v2
            if (this.queryParams.dateType === 'week') {
              // 是周的处理逻辑
              findI = moment(this.queryParams.dateRange[0]).format('YYYY') + v2.split('第').join('').split('周')[0]
              if (findI.includes(v1.week)) {
                item.push(v1.badSeconds)
              } else {
                item.push('')
              }
            } else if (this.queryParams.dateType === 'month') {
              // 是月的处理逻辑
              findI = v2.split('-').join('') + 'badSeconds'
              if (this.isShow(v1KesArr, findI)) {
                let i = this.isShow(v1KesArr, findI)
                item.push(v1[i])
              } else {
                item.push('')
              }
            } else {
              if (findI.includes(v1.date)) {
                item.push(v1.badSeconds)
              } else {
                item.push('')
              }
            }
          }
        })
        result.push(item)
      })
      return result
    },
    isShow (arr, item) {
      let flag = ''
      arr.forEach(i => {
        if ([item].includes(i)) {
          flag = i
        }
      })
      return flag
    },
    getDate (date) {
      return moment(date).format('YYYYMMDD')
    },
    setOprofNum (val) {
      this.oprof_start.num = this.queryParams.devices[0] === 'all' ? val : this.queryParams.devices.length
    },
    // 初始化查询接口
    getDailyBadReport () {
      this.location.workshop = this.queryData.location.label
      this.location.reason = this.causeStopType === '1' ? this.rowParams.causeGroupName : this.rowParams.causeName
      this.location.dateTime = this.queryParams.dateRange.map(v => moment(v).format('YYYY-MM-DD')).join('~')
      const params = {
        pageNum: this.pagination.page,
        pageSize: this.pagination.rowsPerPage,
        schemeLevel: this.queryData.location.level,
        deviceIds: this.queryData.devices[0] === 'all' ? [] : this.queryData.devices,
        schemeLevelId: this.queryData.location.id,
        startDate: this.queryData.dateData[0],
        endDate: this.queryData.dateData[1],
        causeId: this.causeStopType === '2' ? this.rowParams.causeId : null,
        causeGroupId:
          this.causeStopType === '1' ? this.rowParams.causeGroupId : null,
        dateType: this.queryData.dateType,
        productIds: this.queryData.product,
        type: this.causeStopType
      }
      this.isTableLoading = true
      getDailyBadReport(params).then(res => {
        this.isTableLoading = false
        const ret = res.data
        // 总条数
        // 日周月 格式
        const dateType = this.queryData.dateType
        // 原因类别还是原因查看
        // this.causeStopType
        // 日期当中区分日周月字段
        const member = {
          date: 'date',
          week: 'week',
          month: 'yearMonth'
        }
        ret.map((v, i) => {
          const item = v
          item.productName = v.productName || '--'
        })
        //
        this.tableColumns = this.setColsHeader(this.queryData._getTableHeader)
        this.tableData = this.getCause(ret, member[dateType])
        console.log(this.tableData)
        this.colsData = this.queryData._getTableHeader
      })
    },
    setColsHeader (val) {
      const r = val.reduce((arr, item) => {
        arr.push(
          //   {
          //   label: '生产产量',
          //   name: item.name + 'totalFinishSeconds',
          //   field: item.name + 'totalFinishSeconds',
          //   align: 'center',
          //   cols: 2
          // },
          {
            label: '不良数量',
            name: item.name + 'badSeconds',
            field: item.name + 'badSeconds',
            align: 'center',
            date: item.name,
            cols: 2,
            isBtn: true
          })
        return arr
      }, [])
      return r
    },
    //
    getCause (val, dateType) {
      const p = val.map(v => {
        const item = v
        item[v[dateType] + 'totalFinishSeconds'] = v.totalFinishSeconds
        item[v[dateType] + 'badSeconds'] = v.badSeconds
        return item
      })
      const combined = p.reduce((acc, cur) => {
        const target = acc.find(e => e.productId === cur.productId)
        if (target) {
          Object.assign(target, cur)
        } else {
          acc.push(cur)
        }
        return acc
      }, []).map((k, i) => {
        const y = k
        y.indexId = i + 1
        return y
      })
      return combined
    },
    onLookDetail (row, item) {
      const member = {
        date: 'date',
        week: 'week',
        month: 'yearMonth'
      }
      this.defectRowData = {
        ...row,
        ...this.location,
        ...this.rowParams,
        ...this.queryData,
        causeStopType: this.causeStopType
      }
      const dateType = member[this.defectRowData.dateType]
      this.defectRowData[dateType] = item.date
      this.isDefect = true
    }
  }
}
</script>
<style scoped>
.btn {
  margin-top: -5px;
}
</style>
